<?php
/**
 * Created by PhpStorm.
 * User: 程序猴
 * Date: 2018/4/16
 *  Q Q: 505413
 * Time: 13:15
 */

namespace app\admin\controller;
use app\admin\controller\Base;

class Themes extends Base
{
    //主题列表
    public function index()
    {
        $dir = ROOT_PATH . 'themes/'; //主题目录
        //PHP遍历文件夹下所有文件
        $handle=opendir($dir.".");
        $themesName = [];
        while (false !== ($file = readdir($handle)))
        {
            if ($file != "." && $file != "..") {
                $themesName[] = $file;
            }
        }
        //读取当前主题
        $filename = APP_PATH . '/index/extra/template.php';
        $str = file_get_contents($filename);
        $res = preg_match('/themes\/(\S*)\//' , $str, $matches); // $str 读取到的字符串
        //print_r($res);
        if($res) {
            $currtheme = $matches[1];
        }
        $this->assign('currtheme',$currtheme);
        $this->assign('themesName',$themesName);
        return $this->fetch();
    }

    //主题切换
    public function themesSwitch()
    {
        if(request()->isAjax())
        {
            $name = input('post.themes');
            if(empty($name)){
                return json(['code' => -1, 'url' => 'themes/index', 'msg' => '参数错误']);
            }
            $name = 'themes/' . $name . '/';
            $filename = APP_PATH . '/index/extra/template.php';
            $put = file_get_contents($filename);
            if(empty($put)){
                return json(['code' => -2, 'url' => 'themes/index', 'msg' => '模板文件内容有误']);
            }
            $out = preg_replace('/themes\/(\S*)\//', $name, $put, 1);
            $res = file_put_contents($filename, $out);
            if($res === false) {
                return json(['code' => -3, 'url' => 'themes/index', 'msg' => '模板修改失败']);
            } else {
                return json(['code' => 1, 'url' => 'themes/index', 'msg' => '模版切换成功']);
            }
        }

    }


}